import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 椭圆的参数方程
def x(t, a=2):
    return a * np.cos(t)

def y(t, b=1):
    return b * np.sin(t)

# 导数函数
def dx_dt(t, a=2):
    return -a * np.sin(t)

# 参数方程下的面积计算
def parametric_area(x, y, dx_dt, alpha, beta, a=2, b=1):
    """
    计算参数方程表示的曲线围成的面积
    """
    def integrand(t):
        return y(t, b) * dx_dt(t, a)
    
    area, error = integrate.quad(integrand, alpha, beta)
    return abs(area), error  # 取绝对值确保面积为正

# 计算椭圆面积
a, b = 2, 1
area, error = parametric_area(x, y, dx_dt, 0, 2*np.pi, a, b)

print(f"椭圆面积: {area:.6f}")
print(f"理论面积: {np.pi * a * b:.6f}")

# 可视化椭圆
t = np.linspace(0, 2*np.pi, 1000)
x_vals = x(t, a)
y_vals = y(t, b)

plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, 'b-', linewidth=2)
plt.fill(x_vals, y_vals, alpha=0.3, color='blue')
plt.title(f'椭圆 $\\frac{{x^2}}{{{a}^2}} + \\frac{{y^2}}{{{b}^2}} = 1$')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.axis('equal')
plt.show()